package org.thanos.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thanos.demo.entity.Person;
import org.thanos.demo.service.OdmPersonRepo;

import java.util.List;

@RestController
public class DemoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private OdmPersonRepo odmPersonRepo;

    @GetMapping(value = "/findOne")
    public List<Person> findByCn(@RequestParam(name = "cn") String cn, ServerHttpResponse response) {
        try {
            List<Person> result = odmPersonRepo.findByCn(cn);
            response.setStatusCode(HttpStatus.OK);
            return result;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            return null;
        }
    }

    @PostMapping(value = "/create")
    public Person create(@RequestParam(name = "cn") String cn, @RequestParam(name = "sn") String sn, @RequestParam(name = "userPassword") String userPassword, ServerHttpResponse response) {
        try {
            Person person = new Person();
            person.setCn(cn);
            person.setSn(sn);
            person.setUserPassword(userPassword);
            person = odmPersonRepo.create(person);
            response.setStatusCode(HttpStatus.OK);
            return person;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            return null;
        }
    }


    @PostMapping(value = "/update")
    public Person update(@RequestParam(name = "cn") String cn, @RequestParam(name = "sn") String sn, @RequestParam(name = "userPassword") String userPassword) {
        Person person = new Person();
        person.setCn(cn);
        person.setSn(sn);
        person.setUserPassword(userPassword);
        return odmPersonRepo.modifyPerson(person);
    }

    @PostMapping(value = "/delete")
    public void delete(@RequestParam(name = "cn") String cn) {
        Person person = new Person();
        person.setCn(cn);
        odmPersonRepo.deletePerson(person);
    }
}
